from flask import render_template, request, Blueprint
from result.result import Result
from service.yolo_service import YoloService
from flask_jwt_extended import jwt_required
from common.my_socketio import socketio
import concurrent.futures

yolo_api = Blueprint('yolo_api', __name__)


@yolo_api.route("", methods=['POST'])
@jwt_required()
def yolo():
    # model = YOLOv10.from_pretrained(f'pt/{model_id}')
    data = request.get_json()
    return YoloService.yolo(data)

    # image = data['image']
    # video = data['video']
    # # model_id = data['model_id']
    # image_size = data['image_size']
    # conf_threshold = data['conf_threshold']
    #
    # model = YOLOv10(r'/pt/yolov10n.pt')
    # if image:
    #     results = model.predict(source=image, imgsz=image_size, conf=conf_threshold, save=True)
    #     print(results)
    #     annotated_image = results[0].plot()
    #     retval, buffer = cv2.imencode('.webp', annotated_image)
    #     image_bytes = buffer.tobytes()
    #     # os.remove(image)
    #     base64_image = base64.b64encode(image_bytes).decode('utf-8')
    #     response_data = {
    #         'image': f'data:image/webp;base64,{base64_image}'
    #     }
    #     # return send_file(BytesIO(image_bytes), mimetype='image/webp')
    #     # return annotated_image[:, :, ::-1], None
    #     # return annotated_image, None
    #     return jsonify(response_data)

    # else:
    #     video_path = tempfile.mktemp(suffix=".webm")
    #     with open(video_path, "wb") as f:
    #         with open(video, "rb") as g:
    #             f.write(g.read())
    #
    #     cap = cv2.VideoCapture(video_path)
    #     fps = cap.get(cv2.CAP_PROP_FPS)
    #     frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    #     frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    #
    #     output_video_path = tempfile.mktemp(suffix=".webm")
    #     out = cv2.VideoWriter(output_video_path, cv2.VideoWriter_fourcc(*'vp80'), fps, (frame_width, frame_height))
    #
    #     while cap.isOpened():
    #         ret, frame = cap.read()
    #         if not ret:
    #             break
    #
    #         results = model.predict(source=frame, imgsz=image_size, conf=conf_threshold)
    #         annotated_frame = results[0].plot()
    #         out.write(annotated_frame)
    #
    #     cap.release()
    #     out.release()
    #     os.remove(video)
    #
    #     return None, output_video_path


# @yolo_api.route("/upload", methods=['POST'])
# @jwt_required()
# def upload_image():
#     # 生成保存文件的目录，如果不存在则创建
#     save_dir = '../../uploads'
#     if not os.path.exists(save_dir):
#         os.makedirs(save_dir)
#     # 清除save_dir下的文件
#     for filename in os.listdir(save_dir):
#         file_path = os.path.join(save_dir, filename)
#         try:
#             # 删除文件
#             os.remove(file_path)
#         except Exception as e:
#             print(f"删除文件 {file_path} 时出错: {e}")
#
#     if 'file' not in request.files:
#         return jsonify({'error': 'No file part'}), 400
#     file = request.files['file']
#     if file.filename == '':
#         return jsonify({'error': 'No selected file'}), 400
#     if file:
#         # 保存文件
#         filename = file.filename
#         file_path = os.path.join(save_dir, filename)
#         file.save(file_path)
#         return jsonify({'message': 'File uploaded successfully', 'file_path': file_path}), 200


# @yolo_api.route("/api_test", methods=["GET", "POST"])
# @jwt_required()
# def my_test():
#     if request.method == "GET":
#         email = get_jwt_identity()
#         return Result.success_data(email)
#     elif request.method == "POST":
#         data = request.get_json()
#         print(data)
#         email = get_jwt_identity()
#         return Result.success_data(email)

# @yolo_api.route("/test", methods=["GET"])
# def mytest():
#     return render_template("test.html")


clients = []
# executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)


@socketio.on('connect')
def handle_connect():
    # 连接建立时的逻辑
    print(f'{request.sid}客户端已经连接')
    clients.append(request.sid)
    # print(clients)
    return Result.success()
    # 可以选择发送欢迎消息给客户端
    # emit('welcome', {'message': 'Welcome to the WebSocket server!'})


@socketio.on('disconnect')
def handle_disconnect():
    # 连接断开时的逻辑
    print(f'{request.sid}客户端断开连接')
    clients.remove(request.sid)
    return Result.success()


@socketio.on('video_frame')
def handle_video_frame(frame_data):
    # print(request.sid)
    if request.sid in clients:
        YoloService.handle_video_frame(frame_data, request.sid)
        # def process_frame():
        #     # print("running")
        #     YoloService.handle_video_frame(frame_data, request.sid)
        # # 提交任务到线程池
        # executor.submit(process_frame)
